package test._interface.service.impl;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import dingding.dao.configInformation;
import test._interface.service.ItestService;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class testServiceImpl implements ItestService {
    @Override
    public  void DingTalkExample(configInformation config, String content) throws ApiException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        Long timestamp = System.currentTimeMillis();
        String secret = config.getSecret();
        String stringToSign = timestamp + "\n" + config.getSecret();
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
//            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");UTF-8
        String sign = URLEncoder.encode(new String(Base64.getEncoder().encodeToString(signData)), "UTF-8");
//        System.out.println(sign);
//        https://oapi.dingtalk.com/robot/send?access_token=XXXXXX&timestamp=XXX&sign=XXX
        String webhook = config.getWebhook() + "&timestamp=" + timestamp + "&sign=" + sign;
        DefaultDingTalkClient client = new DefaultDingTalkClient(webhook);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("text");
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(content);
        request.setText(text);

        try {
            OapiRobotSendResponse response = client.execute(request);
            if (response.isSuccess()) {
//                System.out.println("Message sent successfully!");
                config.setDingdingExceptionErr(null);
            } else {
                String Errmsg = "发送钉钉消息错误: " + response.getErrmsg()+"\n请核对secret加密！";
                config.setDingdingExceptionErr(Errmsg);
//                System.out.println(147+Errmsg);
            }
        } catch (ApiException e) {
            String ERR = "钉钉错误: "+e+"\n请核对webhook地址！";
//            System.out.println(ERR);
//            e.printStackTrace();
            config.setDingdingExceptionErr(ERR);
        }


    }

}
